package com.ljt.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljt.response.Result;
import com.ljt.response.ResultCode;
import com.ljt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功的处理类
 */
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JWTUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        AccountUser user = (AccountUser)authentication.getPrincipal();
        Result result = Result.ok()
                .data("username",user.getUsername())
                .data("id",user.getId())
                .message(ResultCode.LOGIN_SUCCESS.getMessage());
        //处理编码方式，防止中文乱码的情况
        response.setContentType("text/json;charset=utf-8");

        // 生成jwt
        String jwt = jwtUtil.generateToken(authentication.getName());
        response.setHeader(jwtUtil.getHead(), jwt);
        //塞到HttpServletResponse中返回给前台
        //这是springboot中jackson给我们提供的一种能将类或者其他对象转成json的方式
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
